

class CourseController extends BaseController{
    def beforeInterceptor = [action:this.auth]
    
    def index = { redirect(action:list,params:params) }

    // the delete, save and update actions only accept POST requests
    static allowedMethods = [delete:'POST', save:'POST', update:'POST']

    def list = {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
        def access = session.access
        access.refresh()

        def list = access.getList("course")

        [ courseInstanceList: list, courseInstanceTotal: list.count() ]
    }

    def show = {
        def courseInstance = Course.get( params.id )

        if(!courseInstance) {
            flash.message = "Course not found with id ${params.id}"
            redirect(action:list)
        }
        else { 
            def access = session.access
            access.refresh()
            /*
            if(access.checkAccess("course", "show", courseInstance.area.id)){
                return [ courseInstance : courseInstance, numberOfEmployees: courseInstance.getListOfEmployees().size()]
            }
            else{
                flash.message = "Missing Authorization!"
                redirect(action:list)
            }
            */
           return [
               courseInstance : courseInstance,
               numberOfEmployees: courseInstance.getListOfEmployees().size(),
               numberOfParticipants : courseInstance.allParticipants().size()
           ]
        }
    }

    def delete = {
        def courseInstance = Course.get( params.id )
        if(courseInstance) {
            def access = session.access
            access.refresh()
            def area = Area.get(courseInstance.area.id)
            if(access.checkAccess("course", "delete", area.container.id)){
                try {
                    courseInstance.delete(flush:true)
                    flash.message = "Course ${params.id} deleted"
                    redirect(action:list)
                }
                catch(org.springframework.dao.DataIntegrityViolationException e) {
                    flash.message = "Course ${params.id} could not be deleted"
                    redirect(action:show,id:params.id)
                }
            }
            else{
                flash.message = "Missing Authorization!"
                redirect(action:list)
            }

        }
        else {
            flash.message = "Course not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def edit = {
        def courseInstance = Course.get( params.id )

        if(!courseInstance) {
            flash.message = "Course not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            def access = session.access
            access.refresh()
            if(access.checkAccess("course", "edit", courseInstance.area.id)){
                return [ courseInstance : courseInstance ]
            }
            else{
                flash.message = "Missing Authorization!"
                redirect(action:list)
            }
        }
    }

    def update = {

        def courseInstance = Course.get( params.id )

        //Check that date of birth is correct
        if(params.date_month.equals("4")||params.date_month.equals("6")||params.date_month.equals("9")||params.date_month.equals("11")){
            if(params.date_day.equals("31")){
                    params.date_month = "ab"
            }
        }

        if(params.date_month.equals("2")){ // check february month
            if(params.date_day.equals("31")||params.date_day.equals("30")){
                    params.date_month = "ab"
            }
        }
        
        if(courseInstance) {
            if(params.version) {
                def version = params.version.toLong()
                if(courseInstance.version > version) {
                    
                    courseInstance.errors.rejectValue("version", "course.optimistic.locking.failure", "Another user has updated this Course while you were editing.")
                    render(view:'edit',model:[courseInstance:courseInstance])
                    return
                }
            }
            courseInstance.properties = params
            if(!courseInstance.hasErrors() && courseInstance.save()) {
                flash.message = "Course ${params.id} updated"
                redirect(action:show,id:courseInstance.id)
            }
            else {
                render(view:'edit',model:[courseInstance:courseInstance])
            }
        }
        else {
            flash.message = "Course not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def create = {
        def access = session.access
        access.refresh()
        if(access.checkAccess("course", "create", null)){
            def courseInstance = new Course()
            courseInstance.properties = params
            return ['courseInstance':courseInstance]
        }
        else{
            flash.message = "Missing Authorization!"
            redirect(action:list)
        }
    }

    def save = {
        //Check that date of birth is correct
        if(params.date_month.equals("4")||params.date_month.equals("6")||params.date_month.equals("9")||params.date_month.equals("11")){
            if(params.date_day.equals("31")){
                    params.date_month = "ab"
            }
        }

        if(params.date_month.equals("2")){ // check february month
            if(params.date_day.equals("31")||params.date_day.equals("30")){
                    params.date_month = "ab"
            }
        }
        
        def courseInstance = new Course(params)
        def area = Area.get(courseInstance.area.id)
        def access = session.access
        access.refresh()
        if(access.checkAccess("course", "save", area.container.id)){
            if(!courseInstance.hasErrors() && courseInstance.save()) {
                flash.message = "Course ${courseInstance.id} created"
                redirect(action:show,id:courseInstance.id)
            }
            else {
                render(view:'create',model:[courseInstance:courseInstance])
            }
        }
        else{
            flash.message = "Missing Authorization!"
            redirect(action:list)
        }
    }

     def delete_employee = {
        [ employeeList: Course.get(params.id).getListOfEmployees(), id: params.id ]
    }

    def save_deleted_employee = {
        String[] del = request.getParameterValues("employeeid")
        def courseInstance = Course.get(params.id)
        for(String x : del){
            courseInstance.delEmployee(Employee.get(x))
        }
        flash.message = "Employees deleted from the course"
        redirect(action:show, id : params.id)
    }

    /*def add_employee = {
        def p = Course.get(params.id);
        ArrayList l = new ArrayList();
        for(Employee e : Employee.list()){
//TODO Modification in order to avoid employee from other container to show up there
            if(!p.getListOfEmployees().contains(e)){
                l.add(e);
            }
        }
        render(view:'add_employee',model:[ employeeList: l, courseid: params.id ])
    }*/

    def add_employee = {
        def courseInstance = Course.get(params.id);
        ArrayList l = new ArrayList();
            // test if the project is available in current mode
                for(Employee e : Employee.list()){
                    //TODO Modification in order to avoid employee from other container to show up there
                    if(!courseInstance.getListOfEmployees().contains(e)){
                        l.add(e);
                    }
                }
                render(view:'add_employee',model:[ employeeList: l, courseid: params.id ])
    }



    def save_added_employee = {
        String[] vals = request.getParameterValues("employeeid");
        def courseInstance = Course.get(params.courseid)
        if (courseInstance) {
            for(String v : vals){
                def employee = Employee.get(v);
                if(employee == null) {
                    System.out.println(v + " fel!");
                }
                else{
                    courseInstance.addEmployee(employee);
                }
            }
            if(courseInstance.save(flush:true,validate:false)) {

                if(vals && vals.length==0){
                    flash.message = "No employees added."
                }
                else if(vals && vals.length == 1){
                    flash.message = "New employee added."
                }
                else if(vals && vals.length >= 2){
                    flash.message = "New employee added."
                }
                else
                {
                    flash.message = "No employees added."
                }
            }
            else{
                flash.message = "Cannot add new employee, no course found."

                courseInstance.errors.each {
                    println (it);
                }


            }
            redirect(action:show, id : params.courseid)
        }
        else{
            flash.message = "Course id ${params.courseid} not found"
            redirect(action:list)
        }

    }

    def changeMode = {
        //System.out.println("-"+session.mode+"-")
        Date d = new Date()
        if((session.mode==null)||(!session.mode.equalsIgnoreCase("budget"))){
              session.mode="budget"
        }
        else{
            session.mode="sandbox"
        }
        //System.out.println("-"+session.mode+"-")

        flash.message = "Mode changed"
        if(params.idCourse.equals("null")){
            redirect(controller:params.currentController,action:params.currentView)
        }
        else{
            redirect(controller:params.currentController,action:params.currentView, id:params.idCourse)
        }
    }


    /** Add participant **/
    def add_participant = {
        def courseInstance = Course.get(params.id);
        if(courseInstance?.schedules.size() >0){
            ArrayList l = new ArrayList();
            // test if the project is available in current mode
            for(Employee e : Employee.list()){
                //TODO Modification in order to avoid employee from other container to show up there
                if(!courseInstance.allParticipants().contains(e)){
                    l.add(e);
                }
            }
            return [ participantList: l, courseid: params.id ]
        }
        else{
            flash.message = "Cannot add a participant - No schedule are created in this course.";
            redirect(action:"show", id:params.id);
        }
    }



    def save_added_participant = {
        String[] vals = request.getParameterValues("participantIds");
        Schedule s = Schedule.get(request.getParameterValues("scheduleId"));
        def courseInstance = Course.get(params.courseid);
        if( (!request.getParameterValues("scheduleId")) || (s == null) ){
            flash.message = "You need to select a schedule."
            redirect(action:"add_participant",params:["courseid":params.courseid])
        }
        if (courseInstance && courseInstance.schedules.contains(s)) {
            for(String v : vals){
                def employee = Employee.get(v);
                if(employee == null) {
                    System.out.println(v + " fel!");
                }
                else{
                    s.addToParticipants(employee);
                    s.save(flush:true);
                }
            }
            if(courseInstance.save(flush:true,validate:false)) {

                if(vals && vals.length==0){
                    flash.message = "No participants added.";
                }
                else if(vals && vals.length == 1){
                    flash.message = "New participant added."
                }
                else if(vals && vals.length >= 2){
                    flash.message = "New participants added.";
                }
                else
                {
                    flash.message = "No participant added.";
                }
            }
            else{
                flash.message = "Cannot add new participant." //  no course found

                courseInstance.errors.each {
                    println (it);
                }


            }
            redirect(action:show, id : params.courseid)
        }
        else{
            flash.message = "Course id ${params.courseid} not found"
            redirect(action:list)
        }

    }

    def add_schedule = {
        redirect(controller:"schedule",action:"create",params:["courseid": params.id]);
    }

    def updateHours = {
        Double f = Double.parseDouble(params.figure);
        Whoa w = Whoa.get(params.whoaId);
        if(params.type == "updateHours"){
            w.hours = f;
        }
        if(w.save(flush:true)){

        }
        else{

        }
        redirect(controller:"project",action:"blank");
         //render(view:'show',model:[ projectInstance: projectInstance ])

    }

}
